#!/usr/bin/env python
#coding:utf-8

import tornado
from ..baseHandler import BaseHandler
from bson import ObjectId
from ..error import ErrorHandler

class MessagesHandler(BaseHandler):

    #获取用户所有消息接口
    @tornado.gen.coroutine
    def get(self,message_type,objectId):
        #分类型获取用户的所有消息类容
        if not objectId:
            return ErrorHandler.write_error(self,status_code=101,message="缺少ID信息")
        try:
            _id = ObjectId(objectId)
        except Exception as e:
            return  ErrorHandler.write_error(self,status_code=102,message=str(e))


        if not message_type:
            return ErrorHandler.write_error(self,status_code=101,message="消息type不能为空")

        #根据请求的messages_type获取不同的数据
        messages = {}
        if message_type == 'system':
            messages = yield self.db.message.find({'user':objectId,'message_type':'system'}).to_list(10)
        if message_type == 'user':
            messages = yield self.db.message.find({'user':objectId,'message_type':'user'}).to_list(10)
        if message_type == 'detail':
            messages = yield self.db.message.find_one({'_id':_id})
        if message_type == 'comment':
            messages = yield self.db.message.find({'user':objectId,'message_type':'comment'}).to_list(10)
        if message_type == 'all':
            self._check_op_access()
            if self.access:
                messages = yield self.db.message.find({'user':objectId}).to_list(10)
            else:
                return ErrorHandler.write_error(self,status_code=101,message="验证用户身份出错，请重新登录")

        #检查结果集是否为空
        if len(messages) == 0:
            #不论是错误还是没有数据,data返回为空
            return self.response_msg(200,"获取成功",[])
        else:
            return self.response_msg(200,"获取成功",self.find_formart(messages))


handlers = [(r"/message/(system|user|detail|comment|all)/(.*)",MessagesHandler),
            ]